

<template>
  <div class="container">
    <div class="search-div">
      <el-row>
        <el-col span="6">
          <el-input placeholder="请输入院校名称" v-model="searchParam.name" clearable></el-input>
        </el-col>
        <el-col span="3">
          <el-button style="background-color: #ff5600; color: #ffffff; width: 80%" @click="queryData"> 搜索 </el-button>
        </el-col>
        <el-col span="3">
          <el-button style="color: #ff5600; width: 80%" @click="showPredictResult">
            <i class="fa-solid fa-fire-flame-simple" style="color: #ff5600;"></i>测录取概率
          </el-button>
        </el-col>

        <el-col span="3">
          <el-button v-show="role === '管理员'" style="color: #ff5600; width: 80%" @click="triggerFileInput">
            <i class="fa-solid fa-plus" style="color: #ff5600;"></i>上传数据
          </el-button>
          <input type="file" ref="fileInput" style="display: none" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @change="handleFileChange">
        </el-col>
      </el-row>
      <div style="margin: 20px 0;">
        <el-row>
          <el-col span="2">
            <el-button type="text" style="color: black" size="mini">院校所属 ></el-button>
          </el-col>
          <el-col span="2">
            <el-button size="mini" type="text" :class="{ yuanxiao, active: yuanxiao === '全部' }" @click="setYuanxiao('全部')">全部</el-button>
          </el-col>
          <el-col span="15">
            <el-row>
              <el-col v-for="i in yuanxiaoArr" :key="i" span="2">
                <el-button size="mini" type="text" :class="{ yuanxiao, active: yuanxiao === i }" @click="setYuanxiao(i)">{{i}}</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col span="2">
            <el-button size="mini" type="text" style="color: black">院校类型 ></el-button>
          </el-col>
          <el-col span="2">
            <el-button size="mini" type="text" :class="{ yuanxiao, active: yxType === '全部' }" @click="setYxType('全部')">全部</el-button>
          </el-col>
          <el-col span="15">
            <el-row>
              <el-col v-for="i in yxTypeArr" :key="i" span="2">
                <el-button size="mini" type="text" :class="{ yuanxiao, active: yxType === i }" @click="setYxType(i)">{{i}}</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col span="2">
            <el-button size="mini" type="text" style="color: black">办学类型 ></el-button>
          </el-col>
          <el-col span="2">
            <el-button size="mini" type="text" :class="{ yuanxiao, active: bxType === '全部' }" @click="setBxType('全部')">全部</el-button>
          </el-col>
          <el-col span="15">
            <el-row>
              <el-col v-for="i in bxTypeArr" :key="i" span="3">
                <el-button size="mini" type="text" :class="{ yuanxiao, active: bxType === i }" @click="setBxType(i)">{{i}}</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col span="2">
            <el-button size="mini" type="text" style="color: black">院校特色 ></el-button>
          </el-col>
          <el-col span="2">
            <el-button size="mini" type="text" :class="{ yuanxiao, active: yxts === '全部' }" @click="setYxts('全部')">全部</el-button>
          </el-col>
          <el-col span="15">
            <el-row>
              <el-col v-for="i in yxtsArr" :key="i" span="3">
                <el-button size="mini" type="text" :class="{ yuanxiao, active: yxts === i }" @click="setYxts(i)">{{i}}</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
      <el-divider></el-divider>
      <div>
        <el-card v-for="school in schoolList" :key="school.id" class="box-card" style="margin: 5px 0">
          <div style="height: 80px" @click="showDetailDialog(school)">
            <el-row>
              <el-col span="4">
                <el-avatar :size="80" src="https://empty" @error="errorHandler">
                  <img :src="school.icon"/>
                </el-avatar>
              </el-col>
              <el-col span="20">
                <el-row style="height: 30px; line-height: 30px">
                  <el-col span="15">
                    <div style="font-size: x-large">{{school.name}}</div>
                  </el-col>
                  <el-col span="5">
                    <el-tag type="success">{{school.address}}</el-tag>
                  </el-col>
                  <el-col span="2">
                    <el-tag type="primary">
                      <el-link type="primary" :underline="false" style="font-size: 12px" :href="school.website" target="_blank">学校官网</el-link>
                    </el-tag>
                  </el-col>
                  <el-col span="2">
                    <el-tag type="primary">录取概率</el-tag>
                  </el-col>
                </el-row>
                <el-row style="height: 30px; line-height: 30px; font-size: large;">
                  <el-col span="20">
                    <div style="padding: 20px 0 0 0">
                      <span>{{school.level}}</span>
                      <el-divider direction="vertical"></el-divider>
                      <span>综合类</span>
                      <el-divider direction="vertical"></el-divider>
                      <span>{{school.type}}</span>
                      <el-divider direction="vertical"></el-divider>
                      <span>{{school.attr}}</span>
                      <el-divider v-if="school.attr" direction="vertical"></el-divider>
                      <span>强基计划</span>
                    </div>
                  </el-col>
                  <el-col span="4">
                    <div style="padding: 20px 0 0 0">
                      <el-button type="success" size="mini" icon="el-icon-star-off" circle @click="addLoveSchool(school)"></el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>

      <div style="margin: 10px">
        <el-pagination
            background
            :current-page.sync="pageParam.page"
            @current-change="changePage"
            layout="prev, pager, next"
            :total="pageParam.total">
        </el-pagination>
      </div>

      <el-dialog title="志愿推荐结果" :visible.sync="predictDialogVisible">
        <div style="padding: 0 10px">
          <el-button type="primary" icon="el-icon-download" @click="exportToExcel">下载</el-button>
        </div>
        <el-table :data="gridData">
          <el-table-column property="sortVal" label="序号" ></el-table-column>
          <el-table-column property="schoolName" label="姓名" ></el-table-column>
          <el-table-column property="professorName" label="专业"></el-table-column>
          <el-table-column property="ratio" label="录取概率"></el-table-column>
        </el-table>
      </el-dialog>

      <el-dialog title="学校详情" :visible.sync="dialogDetailVisible">
        <div>
          <el-row>
            <el-col span="6">
              <el-avatar :size="80" src="https://empty" @error="errorHandler">
                <img :src="sitem.icon"/>
              </el-avatar>
            </el-col>
            <el-col span="18">
              <div style="font-size: 32px; margin-top: 10px"> {{sitem.name}} </div>
            </el-col>
          </el-row>
          <div style="margin: 5px 0">官网: {{sitem.website}} </div>
        </div>
        <div>
          <div style="margin: 10px 0; font-weight: bolder"> 专业分数线 </div>
          <el-table :data="majorData" height="300px">
            <el-table-column property="professorName" label="专业名称" width="150"></el-table-column>
            <el-table-column property="lowerScore" label="录取分数" width="200"></el-table-column>
            <el-table-column property="subject" label="科目" width="200"></el-table-column>
          </el-table>
        </div>

      </el-dialog>

    </div>
  </div>
</template>

<script >
import {searchSchool, recommand, queryRecommend, addLove, loadSchool, queryMajorBySchool} from "@/api/request";
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import axios from "axios";
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'School',
  data() {
    return {

      dialogDetailVisible: false,
      majorData: [],
      sitem: {},


      role: '',
      gridData: [],
      predictDialogVisible: false,
      headers: [
        { key: 'sortVal', title: '序号' },
        { key: 'schoolName', title: '学校' },
        { key: 'professorName', title: '专业' },
        { key: 'ratio', title: '录取概率' }
      ],
      schoolList: [],

      pageParam: {
        page: 1,
        size: 10,
        total: 0,
      },

      searchParam: {
        name: '',
        address: '',
        type: '',
        attr: ''
      },

      yuanxiao: '全部',
      yuanxiaoArr: [
        "北京", "天津", "河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江", "上海", "安徽", "浙江", "江苏" , "福建",
        "江西", "山东", "河南", "湖北", "湖南", "广东", "广西", "海南", "重庆", "四川", "贵州", "云南" , "西藏",
        "陕西", "甘肃", "青海", "宁夏", "新疆"
      ],
      yxType: '全部',
      yxTypeArr: ['综合', '理工','农林','医药','师范','语言','财经','政法','体育','民族','艺术','军事','其他'],
      bxType: '全部',
      bxTypeArr: ['本科', '专科','公办','民办'],
      yxts: '全部',
      yxtsArr: ['985', '211','双一流','教育部直属','中央部委','强基计划', '双高计划'],
    }
  },

  methods: {


    showDetailDialog(item){
      console.log(item)
      queryMajorBySchool(item.name).then(res => {
        this.majorData = res.data
      })
      this.dialogDetailVisible = true
      this.sitem = item
    },

    triggerFileInput() {
      this.$refs.fileInput.click();
    },

    handleFileChange(event) {
      const file = event.target.files[0];
      if (!file) {
        this.$message.error("请选择文件！")
        return;
      }

      const formData = new FormData();
      formData.append('file', file);
      // 使用 Axios 或者 Vue 的 fetch API 来发送文件
      // 假设 '/upload' 是你的文件上传 API
      axios.post( `http://localhost:8085/upload/school`, formData, {
        withCredentials: true,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
          .then((res) => {
            // 处理响应
            console.log(res)
            const path = res.data.data
            // 调用训练模型接口
            loadSchool(path).then(() => {
              this.queryData()
            })
          })
          .catch(error => {
            // 处理错误
            console.error("上传文件出现错误", error);
          });
    },

    // 添加收藏
    addLoveSchool(school){
      const param = {
        'userId': JSON.parse(sessionStorage.getItem('user')).id,
        'schoolId': school.id
      }

      addLove(param).then(res => {
        if (res.code === 200) {
          this.$message.success('收藏成功')
        } else {
          this.$message.warning('您已收藏过该学校')
        }
      })
    },

    exportToExcel() {
      // 根据自定义表头创建表格数据数组
      const worksheetData = [
        this.headers.map(header => header.title), // 表头行
          ...this.gridData.map(item => this.headers.map(header => item[header.key])) // 数据行
      ];

      // 转换数据并导出 Excel
      this.saveExcel(worksheetData, '志愿推荐表格.xlsx');
    },
    saveExcel(worksheetData, fileName) {
      const ws = XLSX.utils.aoa_to_sheet(worksheetData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }

      saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), fileName);
    },

    showPredictResult(){
      const userId = JSON.parse(sessionStorage.getItem('user')).id
      recommand(userId).then(res => {
        if (res.code === 200) {
          queryRecommend(userId).then(r => {
            console.log(r)
            if (r.code === 200) {
              this.gridData = r.data
              for (let i = 0; i < this.gridData.length; i++) {
                this.gridData[i].sortVal = (i + 1)
              }
              this.predictDialogVisible = true;
            }
          })
        }
      })
    },

    setYuanxiao(yx) {
      this.yuanxiao = yx
      if (yx === '全部') {
        this.searchParam.address = ''
      } else {
        this.searchParam.address = yx
      }
      this.queryData()
    },

    setYxType(yx) {
      this.yxType = yx
    },

    setBxType(yx) {
      this.bxType = yx
      if (yx === '全部') {
        this.searchParam.type = ''
      } else {
        this.searchParam.type = yx
      }
      this.queryData()
    },
    setYxts(yx) {
      this.yxts = yx
      if (yx === '全部') {
        this.searchParam.attr = ''
      } else {
        this.searchParam.attr = yx
      }
      this.queryData()
    },

    queryData(){
      searchSchool(this.pageParam, this.searchParam).then(res => {
        console.log(res.data)
        const data = res.data
        this.pageParam.total = data.total
        this.schoolList = data.records
        for (let i = 0; i < this.schoolList.length; i++) {
          this.schoolList[i].icon = "http://localhost:8085/upload/" + encodeURIComponent(this.schoolList[i].icon)
        }
      })
    },

    changePage(index) {
      this.pageParam.page = index
      this.queryData()
    }

  },

  mounted() {
    this.role = JSON.parse(sessionStorage.getItem('user')).role
    this.queryData()
  }
}
</script>

<style scoped>
.yuanxiao {
  color: black;
}

.active {
  color: #ff5600;
}
</style>